<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['activity:budget:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['activity:budget:delete']"
            >删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
          <el-form-item label="活动名称" prop="activityName">
            <el-input
              v-model="queryParams.activityName"
              placeholder="请输入活动名称"
              clearable
              style="width: 240px"
              @change="handleQuery"
            />
          </el-form-item>
          <el-form-item label="预算项目" prop="itemName">
            <el-input
              v-model="queryParams.itemName"
              placeholder="请输入预算项目名称"
              clearable
              style="width: 200px"
              @change="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </template>

      <el-table
        v-loading="loading"
        :data="budgetList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="预算ID" align="center" prop="id" />
        <el-table-column label="活动名称" align="center" prop="activityName" :show-overflow-tooltip="true" />
        <el-table-column label="预算项目" align="center" prop="itemName" :show-overflow-tooltip="true" />
        <el-table-column label="预算金额" align="center" prop="estimatedAmount">
          <template #default="scope">
            {{ formatAmount(scope.row.estimatedAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="实际支出" align="center" prop="actualAmount">
          <template #default="scope">
            {{ formatAmount(scope.row.actualAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="支出日期" align="center" prop="expenseDate" />
        <el-table-column label="支付方式" align="center" prop="paymentMethod">
          <template #default="scope">
            <el-tag :type="getPaymentMethodTag(scope.row.paymentMethod)">
              {{ scope.row.paymentMethod || '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['activity:budget:edit']"
            >修改</el-button>
            <el-button
              type="primary"
              link
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['activity:budget:delete']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 预算信息表单抽屉 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      :size="drawerSize"
      @close="handleCloseDialog"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="活动名称" prop="activityId" v-if="!formData.id">
          <el-select
            v-model="formData.activityId"
            placeholder="请选择活动"
            style="width: 100%"
            filterable
            remote
            :remote-method="remoteSearchActivity"
            :loading="activityLoading"
          >
            <el-option
              v-for="item in activityOptions"
              :key="item.id"
              :label="item.activityName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="预算项目" prop="itemName">
          <el-input
            v-model="formData.itemName"
            placeholder="请输入预算项目名称"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="预算金额" prop="estimatedAmount">
          <el-input-number
            v-model="formData.estimatedAmount"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="实际支出" prop="actualAmount">
          <el-input-number
            v-model="formData.actualAmount"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="支出日期" prop="expenseDate">
          <el-date-picker
            v-model="formData.expenseDate"
            type="date"
            placeholder="选择支出日期"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select
            v-model="formData.paymentMethod"
            placeholder="请选择支付方式"
            style="width: 100%"
          >
            <el-option
              v-for="dict in paymentMethodOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="formData.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="handleCloseDialog">取消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import ActivityAPI from '@/api/activity.api';
import { useAppStore } from '@/store';
import { DeviceEnum } from '@/enums/index.js';

const appStore = useAppStore();
const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));

// 遮罩层
const loading = ref(false);
// 活动选择器加载状态
const activityLoading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 预算列表
const budgetList = ref([]);
// 活动选项
const activityOptions = ref([]);
// 表单引用
const formRef = ref();

// 支付方式选项
const paymentMethodOptions = ref([
  { value: '现金', label: '现金' },
  { value: '微信', label: '微信' },
  { value: '支付宝', label: '支付宝' },
  { value: '银行卡', label: '银行卡' }
]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  activityName: undefined,
  itemName: undefined
});

// 弹窗
const dialog = reactive({
  title: "新增预算",
  visible: false,
});

// 初始表单数据
const initialFormData = {
  id: undefined,
  activityId: undefined,
  itemName: undefined,
  estimatedAmount: 0,
  actualAmount: 0,
  expenseDate: null,
  paymentMethod: undefined,
  notes: ''
};

// 表单数据
const formData = ref({ ...initialFormData });

// 表单校验规则
const rules = reactive({
  activityId: [{ required: true, message: "请选择活动", trigger: "change" }],
  itemName: [{ required: true, message: "请输入预算项目名称", trigger: "blur" }],
  estimatedAmount: [{ required: true, message: "请输入预算金额", trigger: "blur" }]
});

// 获取活动列表
const getActivityList = async () => {
  try {
    const res = await ActivityAPI.getActivityPage({
      pageNum: 1,
      pageSize: 100
    });
    activityOptions.value = res.list;
  } catch (error) {
    console.error('获取活动列表失败', error);
  }
};

// 远程搜索活动
const remoteSearchActivity = async (query) => {
  if (query) {
    activityLoading.value = true;
    try {
      const res = await ActivityAPI.getActivityPage({
        pageNum: 1,
        pageSize: 20,
        activityName: query,
        flag: 1
      });
      activityOptions.value = res.list;
    } catch (error) {
      console.error('搜索活动失败', error);
    } finally {
      activityLoading.value = false;
    }
  } else {
    activityOptions.value = [];
  }
};

// 获取预算列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await ActivityAPI.getActivityBudgetPage(queryParams);
    budgetList.value = res.list;
    total.value = res.total;
  } catch (error) {
    console.error('获取预算列表失败', error);
  } finally {
    loading.value = false;
  }
};

// 格式化金额
const formatAmount = (amount) => {
  if (amount === undefined || amount === null) return '0.00';
  return `¥ ${parseFloat(amount).toFixed(2)}`;
};

// 获取支付方式标签类型
const getPaymentMethodTag = (method) => {
  switch (method) {
    case '现金': return '';
    case '微信': return 'success';
    case '支付宝': return 'primary';
    case '银行卡': return 'info';
    default: return '';
  }
};

// 表单重置
const resetQuery = () => {
  queryParams.pageNum = 1;
  queryParams.activityName = undefined;
  queryParams.itemName = undefined;
  handleQuery();
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 新增按钮操作
const handleAdd = () => {
  dialog.title = "新增预算";
  dialog.visible = true;
  formData.value = { ...initialFormData };
};

// 修改按钮操作
const handleUpdate = (row) => {
  dialog.title = "修改预算";
  dialog.visible = true;
  loading.value = true;
  ActivityAPI.getActivityBudgetForm(row.id).then(res => {
    formData.value = res;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      
      try {
        let res;
        if (formData.value.id) {
          res = await ActivityAPI.updateActivityBudget(formData.value.id, formData.value);
        } else {
          res = await ActivityAPI.addActivityBudget(formData.value);
        }
        
        ElMessage.success(formData.value.id ? '修改成功' : '新增成功');
        handleCloseDialog();
        getList();
      } catch (error) {
        console.error(formData.value.id ? '修改预算失败' : '新增预算失败', error);
        ElMessage.error(formData.value.id ? '修改失败' : '新增失败');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 关闭对话框
const handleCloseDialog = () => {
  dialog.visible = false;
  formRef.value?.resetFields();
  formData.value = { ...initialFormData };
};

// 删除按钮操作
const handleDelete = (row) => {
  const selectedIds = row?.id || ids.value.join(',');
  if (!selectedIds) {
    ElMessage.warning('请选择要删除的预算');
    return;
  }
  
  ElMessageBox.confirm('确认删除所选预算吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await ActivityAPI.deleteActivityBudget(selectedIds);
      ElMessage.success('删除成功');
      getList();
    } catch (error) {
      console.error('删除预算失败', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }).catch(() => {});
};

onMounted(() => {
  // 不再预加载所有活动
   getActivityList();
  getList();
});
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style> 
